<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>可折叠的树形菜单</title>
    <style>
        .tree-menu ul {
            list-style-type: none;
            padding-left: 16px;
        }

        .tree-menu li {
            margin: 5px 0;
        }

        .toggle::before {
            content: '►';
            display: inline-block;
            width: 12px;
            cursor: pointer;
        }

        .nested {
            display: none;
        }

        .active > .nested {
            display: block;
        }

        .active > .toggle::before {
            content: '▼';
        }
    </style>
</head>
<body>

<div id="treeMenuContainer" class="tree-menu"></div>

<script>
    // JSON 数据
    const treeData = [
        {
            name: "文件夹 1",
            children: [
                {name: "文件 1.1"},
                {name: "文件 1.2"},
                {
                    name: "子文件夹 1.3",
                    children: [
                        {name: "文件 1.3.1"},
                        {name: "文件 1.3.2"}
                    ]
                }
            ]
        },
        {
            name: "文件夹 2",
            children: [
                {name: "文件 2.1"},
                {name: "文件 2.2"}
            ]
        }
    ];

    function createTree(container, data) {
        const ul = document.createElement('ul');

        data.forEach(item => {
            const li = document.createElement('li');
            if (item.children && item.children.length) {
                const toggleSpan = document.createElement('span');
                toggleSpan.className = 'toggle';
                toggleSpan.textContent = item.name;
                li.appendChild(toggleSpan);
                li.appendChild(createTree(document.createElement('ul'), item.children));
            } else {
                li.textContent = item.name;
            }
            ul.appendChild(li);
        });

        container.appendChild(ul);
        return container;
    }

    document.addEventListener('DOMContentLoaded', function () {
        const container = document.getElementById('treeMenuContainer');
        createTree(container, treeData);

        const toggles = container.querySelectorAll('.toggle');
        toggles.forEach(function (toggle) {
            toggle.addEventListener('click', function (event) {
                event.preventDefault();
                const nested = this.nextElementSibling;
                if (nested.classList.contains('nested')) {
                    nested.parentElement.classList.toggle('active');
                }
            });
        });
    });
</script>

</body>
</html>